import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/http/api.dart';
import 'package:leader_doctor_flutter/common/http/http_client.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/utils/log_utils.dart';
import 'package:leader_doctor_flutter/common/utils/string_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/common/widget/verify_code_exception_help.widget.dart';
import 'package:leader_doctor_flutter/plugins/plugins_messages.g.dart';
import 'package:leader_doctor_flutter/router/router.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'package:netease_meeting_ui/meeting_ui.dart';

/// @Author lixiaobin
/// @Date 2023/12/5
/// @Description 更换手机号
class ModifyPhoneNumPage extends StatefulWidget {
  const ModifyPhoneNumPage({super.key});

  @override
  State<ModifyPhoneNumPage> createState() => _ModifyPhoneNumPageState();
}

class _ModifyPhoneNumPageState extends State<ModifyPhoneNumPage> {
  final _smsTextEditingController = TextEditingController();

  int _countValue = 0;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _smsTextEditingController.addListener(() {
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    var btnIsSelect = _smsTextEditingController.text.isNotEmpty;
    var showNewNumber = StringUtils.showNewNumber(App.instance.userInfo?.phone);
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: CommWidget.getCommAppbar(context),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
              height: 65.w,
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.only(left: 16.w, right: 16.w),
              color: ColorRes.colorEDEDFD,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    padding: EdgeInsets.only(top: 2.w),
                    child: ImageLoader.loadAsset('icon_cp_z_alert.webp', 15.w),
                  ),
                  SizedBox(width: 5.w),
                  Expanded(
                    child: Text(
                      '成功更换手机号码后，登录账号为新手机号，登录密码保持不变！',
                      style: TextStyle(color: ColorRes.color333333, fontSize: 13.sp),
                    ),
                  )
                ],
              )),
          Container(
            height: 56.w,
            alignment: Alignment.centerLeft,
            padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 8.w),
            width: double.infinity,
            child: Text(showNewNumber ?? '', style: TextStyle(color: ColorRes.color666666, fontSize: 15.sp)),
          ),
          CommWidget.buildLine(),
          Container(
            height: 56.w,
            padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 8.w),
            width: double.infinity,
            child: Row(
              children: [
                Expanded(
                    child: TextField(
                  controller: _smsTextEditingController,
                  inputFormatters: [
                    LengthLimitingTextInputFormatter(6),
                    FilteringTextInputFormatter.allow(RegExp(r'[0-9]'))
                  ],
                  decoration: const InputDecoration(hintText: '请输入验证码', border: InputBorder.none),
                )),
                GestureDetector(
                  onTap: () => _getSms(),
                  child: Container(
                      height: 30.w,
                      padding: EdgeInsets.only(left: 10.w, right: 10.w),
                      alignment: Alignment.center,
                      child: Text(_countValue == 0 ? '获取验证码' : '重新获取（${_countValue}s）',
                          style: TextStyle(
                              fontWeight: FontWeight.bold,
                              color: _countValue == 0 ? ColorRes.colorMain : ColorRes.color9A9A9A,
                              fontSize: 15.sp))),
                )
              ],
            ),
          ),
          CommWidget.buildLine(),
          SizedBox(
            height: 10.w,
          ),
          VerifyCodeExceptionHelpWidget(),
          SizedBox(
            height: 52.w,
          ),
          Padding(
              padding: EdgeInsets.only(left: 16.w, right: 16.w),
              child: CommWidget.customBuildBtn("确定", () {
                _updatePwdBySmsCode();
              }, ColorRes.colorMain, ColorRes.colorB8B3FA, 6.w, isSelect: btnIsSelect)),

          // Expanded(
          //     child: GestureDetector(
          //         onTap: () => NativeInterface()
          //             .call(App.instance.serviceInfo?.phone ?? ""),
          //         child: Column(
          //           mainAxisAlignment: MainAxisAlignment.end,
          //           crossAxisAlignment: CrossAxisAlignment.start,
          //           children: [
          //             Row(
          //               mainAxisAlignment: MainAxisAlignment.center,
          //               children: [
          //                 Text('  客服电话：',
          //                     style: TextStyle(
          //                         color: ColorRes.color666666,
          //                         fontSize: 12.sp)),
          //                 Text(App.instance.serviceInfo?.phone ?? '',
          //                     style: TextStyle(
          //                         color: ColorRes.color0065ff,
          //                         fontSize: 12.sp)),
          //               ],
          //             ),
          //             Row(
          //               mainAxisAlignment: MainAxisAlignment.center,
          //               children: [
          //                 Text('客服工作时间：',
          //                     style: TextStyle(
          //                         color: ColorRes.color666666,
          //                         fontSize: 12.sp)),
          //                 Text(
          //                     '工作日${App.instance.serviceInfo?.workingTime ?? ''}',
          //                     style: TextStyle(
          //                         color: ColorRes.color666666,
          //                         fontSize: 12.sp)),
          //               ],
          //             )
          //           ],
          //         ))),
          // SizedBox(
          //   height: 20.w,
          // ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    // 组件销毁时判断Timer是否仍然处于激活状态，是则取消
    if (_timer?.isActive == true) {
      _timer?.cancel();
    }
    super.dispose();
  }

  /// 启动Timer
  _startTimer() {
    const Duration duration = Duration(seconds: 1);
    cancelTimer();

    _timer = Timer.periodic(duration, (timer) {
      _countValue -= 1;
      Log.d(_countValue);
      if (_countValue <= 0) {
        cancelTimer();
      }
      setState(() {});
    });
  }

  void cancelTimer() {
    if (_timer != null) {
      _timer?.cancel();
    }
  }

  /// 获取验证码
  _getSms() async {
    if (_countValue > 0) return;
    var phone = App.instance.userInfo?.phone;
    if (phone == null || phone.isEmpty == true) return;
    var httpRequest = HttpRequest(Api.sendSms, body: {
      'phone': phone,
      "purpose": 'updateLoginNameVerifyCode',
    });
    var httpResponse = await HttpClient.post(httpRequest);
    var serviceResult = ServiceResult<String?>.simple(httpResponse);
    if (serviceResult.success) {
      _countValue = 60;
      _startTimer();
    }
    ToastUtils.showToast(context, serviceResult.responseMsg);
  }

  /// 修改密码
  _updatePwdBySmsCode() async {
    var smsCode = _smsTextEditingController.text;
    if (smsCode.isEmpty) {
      ToastUtils.showToast(context, '请输入验证码');
      return;
    }
    var phone = App.instance.userInfo?.phone;
    var httpRequest = HttpRequest(Api.verifyCode, urlParams: {
      "phoneNum": phone,
      'code': smsCode,
    });
    var httpResponse = await HttpClient.get(httpRequest);
    var serviceResult = ServiceResult<bool?>.simple(httpResponse);
    if (serviceResult.success) {
      context.pushReplacement(PageUrl.bindPhoneNum);
    } else {
      ToastUtils.showToast(context, serviceResult.responseMsg);
    }
  }
}
